// pages/qr/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cancelLogin: false,
    wxUser: null,
    showMakePhone: false,
    showMsgBtn: false,
    isLoading: false,
    sid: '',
    loginBtnDisabled: false,
    disbledBgColor: "background:#2967ff;color:white",
    modelId: null,
    sn: null,
    snTicket: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
    const scancode_time = parseInt(options.scancode_time) // 获取用户扫码时间 UNIX 时间戳
    // const q = "https://www.chenkun.site?token=d779fc27cf6e4caa8ad4a56f1fb57a88&time=1667826454838"
    // const scancode_time = 1665826454
    if (q != null && typeof (q) != 'undefined') {
      let token = this.GetQueryString(q, "token");
      let time = this.GetQueryString(q, "time");
      if (time != null && parseInt(scancode_time) - parseInt(time) / 1000 > 180) {
        this.setData({
          loginBtnDisabled: true,
        })
      } else {
        this.setData({
          sid: token
        })
      }
    }
    if (this.data.sid) {
      app.api.scanAction({
        token: this.data.sid
      }).then(res => {
        this.setData({
          modelId: res.data.modelId,
          sn: res.data.sn,
          snTicket: res.data.snTicket
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.loginBtnDisabled) {
      wx.showToast({
        title: '二维码已经过期',
        icon: 'error'
      })
      this.setData({
        disbledBgColor: "background:#2967ff80;color:white",
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onCancelLogin() {
    this.setData({
      cancelLogin: !this.data.cancelLogin
    })
  },

  onExit() {
    wx.exitMiniProgram({
      complete: function (e) {
      }
    });
  },

  onEnter() {
    wx.switchTab({
      url: '/pages/home/index',
    })
  },
  getUserProfile(e) {
    this.setData({
      isLoading: true
    });
    app.initPage()
      .then(res => {
        let wxUser = app.globalData.wxUser
        if (wxUser != null && wxUser != "") {
          this.setData({
            wxUser: wxUser,
          })
          if(wxUser.nickName == null || wxUser.headimgUrl == null){
            this.wxGetUserInfo()
          }else if(wxUser.phone == null || wxUser.phone == ''){
            this.openMakePhone()
          }else{
            this.openMakePhone()
            this.setData({
                showMsgBtn: true
              })
          }
        } else {
            this.wxGetUserInfo()
        }
      })
  },
  openMakePhone() {
    this.setData({
      showMakePhone: true
    });
  },
  wxGetUserInfo() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (detail) => {
        app.api.wxUserSave(detail)
          .then(res => {
            let wxUser = res.data
            this.setData({
              wxUser: wxUser
            })
            app.globalData.wxUser = wxUser
            this.openMakePhone()
          })
      },
      fail: () => {
        this.setData({
          isLoading: false,
          showMsgBtn: false
        });
      }
    })
  },
  closeMakePhone() {
    this.setData({
      showMakePhone: false,
      isLoading: false
    });
  },
  getPhoneNumber(e) {
    console.log(e.detail.code)
    wx.showLoading({
      title: '处理中',
    })
    var that = this;
    that.closeMakePhone()
    this.setData({
      isLoading: true
    });
    let errMsg = e.detail.errMsg;
    if (errMsg == 'getPhoneNumber:ok') {
      wx.showLoading({
        title: '处理中',
      })
      app.api.getPhoneNumber(wx.getAccountInfoSync().miniProgram.appId, e.detail.code).then(res => {
        if (res.data != "") {
          console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~");
          let data = res.data;
          let modelId = data.modelId;
          let sn = data.sn;
          let snTicket = data.snTicket;
          var phone = data.phone;
          console.log(phone);
          app.globalData.wxUser.phone = phone
          that.setData({
            wxUser: app.globalData.wxUser,
            sn: sn,
            modelId: modelId,
            snTicket: snTicket
          })
          app.api.wxUserPut(app.globalData.wxUser).then(res => {
            console.log(res)
            if (res.data) {
              wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
              })
              that.openMakePhone()
              that.setData({
                showMsgBtn: true
              })
              wx.hideLoading()
            }
          });
        } else {
          wx.showToast({
            title: '获取失败',
            icon: 'error',
            duration: 2000
          })
          that.setData({
            isLoading: false
          })
          wx.hideLoading()
        }
      })
    } else if (errMsg = "fail no permission") {
      wx.hideLoading({
        success: (res) => {
        },
      })
      wx.showToast({
        title: '没有权限',
        icon: 'error',
        duration: 2000
      })
      this.setData({
        isLoading: false
      })
    } else {
      wx.hideLoading({
        success: (res) => {
        },
      })
      wx.showToast({
        title: '获取失败',
        icon: 'error',
        duration: 2000
      })
      this.setData({
        isLoading: false
      })
    }
  },
  sendMessage: function () {
    let _this = this
    wx.requestSubscribeDeviceMessage({
      sn: this.data.sn,
      snTicket: this.data.snTicket,
      modelId: this.data.modelId,
      tmplIds: ['y5v6VYlNXIv-yP7BIKjmwiG2zF8R3wxd0F_Tr9HIf1s'],
      success(res) {
        console.log('[wx.requestSubscribeDeviceMessage success]: ', res)
        // { 'QCpBsp1TGJ1ML-UIwAIMkdXpPGzxSfwJqsKsvMVs3io': 'accept' }
        // app.api.sendMessage({
        //   openId: app.globalData.wxUser.openId,
        //   accessToken: app.globalData.wxUser.accessToken,
        //   sn: _this.data.sn,
        //   model_id: _this.data.modelId
        // }).then(res => {
        //   console.log(res)
          _this.closeMakePhone()
          _this.setData({
            isLoading: false
          })
          wx.switchTab({
            url: '/pages/home/index',
          })
        // })
        wx.login({
          success: function (res) {
            if (res.code) {
              app.api.loginScan({
                jsCode: res.code,
                token: _this.data.sid
              }).then(res => {
                console.log(res)
              })
            }
          }
        })
      },
      fail(res) {
        console.log('[wx.requestSubscribeDeviceMessage fail]: ', res)
        _this.setData({
          isLoading: false,
          showMsgBtn: false
        })
      }
    })

    // wx.requestSubscribeMessage({
    //   tmplIds: ['AKxwPdaPQKv7HfEJP1UPmNYLDNT1q0VDM4AX00xAuNQ'],
    //   success(res) {
    //     app.api.sendMessage({
    //       openId: app.globalData.wxUser.openId,
    //       accessToken: app.globalData.wxUser.accessToken
    //     }).then(res => {
    //       console.log(res)
    //       _this.closeMakePhone()
    //       _this.setData({
    //         isLoading: false
    //       })
    //       wx.switchTab({
    //         url: '/pages/home/index',
    //       })
    //     })
    //     wx.login({
    //       success: function (res) {
    //         if (res.code) {
    //           app.api.loginScan({
    //             jsCode: res.code,
    //             token: _this.data.sid
    //           }).then(res => {
    //             console.log(res)
    //           })
    //         }
    //       }
    //     })
    //   },
    //   complete(res) {
    //     console.log(res)
    //   },
    //   fail(res) {
    //     _this.setData({
    //       isLoading: false,
    //       showMsgBtn: false
    //     })
    //   }
    // })
  },
  GetQueryString: function (options, name) {
    var reg = new RegExp("(^&|)" + name + "=([^&]*)(&|$)", "i");
    var r = options.substr(1).match(reg);
    if (r != null) return (r[2]);
    return null;
  }
})